package com.shiwaixiangcun.customer.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.jaeger.recyclerviewdivider.RecyclerViewDivider;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shiwaixiangcun.customer.GlobalApi;
import com.shiwaixiangcun.customer.GlobalConfig;
import com.shiwaixiangcun.customer.R;
import com.shiwaixiangcun.customer.adapter.AdapterAnnouncement;
import com.shiwaixiangcun.customer.base.BaseActivity;
import com.shiwaixiangcun.customer.entity.NoticeBean;
import com.shiwaixiangcun.customer.entity.PageBean;
import com.shiwaixiangcun.customer.entity.ResponseEntity;
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr;
import com.shiwaixiangcun.customer.utils.JsonUtil;
import com.shiwaixiangcun.customer.widget.ChangeLightImageView;
import com.shiwaixiangcun.customer.widget.CustomLoadMoreView;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author Administrator
 */
public class CommunityAnnouncementActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.back_left)
    ChangeLightImageView mBackLeft;
    @BindView(R.id.tv_page_name)
    TextView mTvPageName;
    @BindView(R.id.lv_community)
    RecyclerView mLvCommunity;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.cl_nodata)
    ConstraintLayout mClNodata;
    private int siteId;
    private int mCurrentPage;
    private int mPageSize;
    private AdapterAnnouncement mAdapterMain;
    private List<AdapterAnnouncement.MultipleItem> mMainList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_community_announcement);
        ButterKnife.bind(this);
        initViewAndEvent();
        initData(mCurrentPage, mPageSize, false);
    }


    private void initViewAndEvent() {
        mBackLeft.setOnClickListener(this);
        mTvPageName.setText("社区公告");
        siteId = (int) AppSharePreferenceMgr.get(mContext, GlobalConfig.CURRENT_SITE_ID, 20);
        mCurrentPage = GlobalConfig.first_page;
        mPageSize = GlobalConfig.page_size;
        mMainList = new ArrayList<>();
        RecyclerViewDivider divider = new RecyclerViewDivider.Builder(mContext)
                .setOrientation(RecyclerViewDivider.VERTICAL)
                .setStyle(RecyclerViewDivider.Style.BETWEEN)
                .setEndSkipCount(1)
                .setMarginLeft(16)
                .setMarginRight(16)
                .setColorRes(R.color.color_divider_0_1)
                .build();
        mLvCommunity.addItemDecoration(divider);
        mAdapterMain = new AdapterAnnouncement(mMainList);
        mLvCommunity.setLayoutManager(new LinearLayoutManager(this));
        mLvCommunity.setAdapter(mAdapterMain);
        mAdapterMain.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                AdapterAnnouncement.MultipleItem item = (AdapterAnnouncement.MultipleItem) adapter.getData().get(position);
                NoticeBean data = item.getData();
                switch (data.getArticleShowType()) {
                    case "ACTIVITY":
                        Bundle bundle = new Bundle();
                        bundle.putInt("activityID", data.getId());
                        readyGo(RegisterDetailActivity.class, bundle);
                        break;
                    default:
                        Intent intent = new Intent(mContext, DetailsActivity.class);
                        intent.putExtra("articleId", data.getId() + "");
                        intent.putExtra("detailTitle", data.getTitle() + "");
                        intent.putExtra("detailContent", data.getSummary());
                        startActivity(intent);
                        break;
                }
            }
        });
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mCurrentPage = 1;
                mAdapterMain.setEnableLoadMore(false);
                initData(mCurrentPage, mPageSize, false);
            }
        });
        mAdapterMain.setLoadMoreView(new CustomLoadMoreView());
        mAdapterMain.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                Log.e(BUG_TAG, "LoadMore");
                if (mRefreshLayout.isRefreshing()) {
                    mRefreshLayout.finishRefresh();
                }
                mCurrentPage++;
                initData(mCurrentPage, mPageSize, true);
            }
        }, mLvCommunity);

    }

    private void initData(int start, int size, final boolean isLoadMore) {

        OkGo.<String>get(GlobalApi.INSTANCE.getArticleListpage())
                .params("siteId", siteId)
                .params("page.pn", start)
                .params("page.size", size)
                .params("position", "COMMUNITY_ANNOUNCEMENT")
                .execute(new StringCallback() {
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        mRefreshLayout.finishRefresh();
                        mAdapterMain.loadMoreFail();
                        mAdapterMain.setEnableLoadMore(true);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        if (mRefreshLayout.isRefreshing()) {
                            mRefreshLayout.finishRefresh();
                        }
                        if (mAdapterMain.isLoading()) {
                            mAdapterMain.loadMoreComplete();
                        }
                        Type type = new TypeToken<ResponseEntity<PageBean<NoticeBean>>>() {
                        }.getType();
                        ResponseEntity<PageBean<NoticeBean>> responseEntity = JsonUtil.fromJson(response.body(), type);
                        if (responseEntity == null) {
                            return;
                        }
                        switch (responseEntity.getResponseCode()) {
                            case 1001:
                                List<NoticeBean> elements = responseEntity.getData().getElements();
                                int size = elements == null ? 0 : elements.size();
                                if (isLoadMore) {
                                    if (size > 0) {
                                        setData(true, elements);
                                    }
                                    if (size == 0 || size < mPageSize) {
                                        mAdapterMain.loadMoreEnd(false);
                                    }
                                } else {
                                    mAdapterMain.setEnableLoadMore(true);
                                    if (size == 0) {
                                        mClNodata.setVisibility(View.VISIBLE);
                                    } else {
                                        mMainList.clear();
                                        setData(false, elements);
                                    }
                                }

                                break;
                            default:
                                break;
                        }
                    }
                });
    }

    /**
     * 设置数据
     *
     * @param isLoadMore 是否加载更多
     * @param elements   数据
     */
    private void setData(boolean isLoadMore, List<NoticeBean> elements) {

        if (isLoadMore) {
            mAdapterMain.loadMoreComplete();
        } else {
            mRefreshLayout.finishRefresh();
        }
        for (NoticeBean bean : elements) {
            AdapterAnnouncement.MultipleItem multipleItem;
            switch (bean.getArticleShowType()) {
                case "ARTICLE_IMAGE":
                    multipleItem = new AdapterAnnouncement.MultipleItem(1, bean);
                    break;
                case "ACTIVE":
                    multipleItem = new AdapterAnnouncement.MultipleItem(3, bean);
                    break;
                case "ACTIVITY":
                    multipleItem = new AdapterAnnouncement.MultipleItem(4, bean);
                    break;
                default:
                    multipleItem = new AdapterAnnouncement.MultipleItem(3, bean);
                    break;
            }
            mMainList.add(multipleItem);
        }
        mAdapterMain.notifyDataSetChanged();


    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.back_left:
                finish();
                break;
            default:
                break;
        }
    }

}
